package com.sunwayworld.basemodule.samplemanage.location.validators;

import com.sunwayworld.basemodule.samplemanage.location.bean.LimsLocationBean;
import com.sunwayworld.basemodule.samplemanage.location.bean.LimsLocationBoardBean;
import com.sunwayworld.basemodule.samplemanage.location.service.LimsLocationBoardService;
import com.sunwayworld.basemodule.samplemanage.location.service.LimsLocationService;
import com.sunwayworld.basemodule.samplemanage.sample.bean.LimsSampleBean;
import com.sunwayworld.basemodule.samplemanage.sample.service.LimsSampleService;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.ArrayUtils;
import com.sunwayworld.framework.utils.CollectionUtils;
import com.sunwayworld.framework.validator.data.DataValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsLocationDeleteValidator implements DataValidator {

    @Autowired
    private LimsLocationService locationService;

    @Autowired
    private LimsLocationBoardService boardService;

    @Autowired
    private LimsSampleService sampleService;

    @Override
    public boolean doValid(Object... args) {
        List<LimsLocationBean> locationBeans;
        if (args[0].getClass().equals(RestJsonWrapperBean.class)) {
            RestJsonWrapperBean wrapper = (RestJsonWrapperBean) args[0];
            locationBeans = wrapper.parse(LimsLocationBean.class);
        } else {
            String group = (String) args[0];
            // 去掉层级，后面板子可以挂在任何层级上
            locationBeans = locationService.selectListByFilter(SearchFilter.instance()
                    .match("group", group).filter(MatchPattern.EQ));
            if(locationBeans.isEmpty()){
                return true;
            }
        }
        // 校验冰箱下是否有板子
        List<Long> ids = locationBeans.stream().map(LimsLocationBean::getId).collect(Collectors.toList());
        List<LimsLocationBoardBean> boardBeans = boardService.getDao().selectListByOneColumnValues(ids, "locationId", ArrayUtils.asList("id"));
        if(!CollectionUtils.isEmpty(boardBeans)){
            this.addConstraintViolation(I18nHelper.getMessage("T_LIMS_LOCATION.DELETE_BOARD_NOT_EMPTY"));
            return false;
        }
        return true;
    }
}
